package com.ruoyi.web.core.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * <pre>
 *    description
 * </pre>
 *
 * @author zhangli
 * @version 1.0
 * @since 2025/7/18
 */
@Slf4j
@Component
public class QueryAddressUtil {

    @AllArgsConstructor
    public static class Location {

        private double lng;

        private double lat;
    }

    @Autowired
    private HttpClient httpClient;

    public Location queryAddress(String address) {
        String url = "https://qryloct.market.alicloudapi.com/lundear/qryaddr?address=" + URLEncoder.encode(address);

        String appcode = "ebb1de38ed3746ab8b6c6458907da200";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            String response = httpClient.doGet(url, headers);
            log.info("请求地址解析:{}", response);
            JSONObject jsonObject = JSON.parseObject(response);
            if (jsonObject.getInteger("status") == 0) {
                JSONObject result = jsonObject.getJSONObject("result");
                JSONObject jsonLocation = result.getJSONObject("location");
                Location location = new Location(jsonLocation.getDouble("lng"), jsonLocation.getDouble("lat"));
                return location;
            }
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return null;
    }

    public double getDistance(Location a, Location b) {
        double R = 6371; // 地球平均半径（单位：千米）
        double dLat = Math.toRadians(b.lat - a.lat); // 纬度差转换为弧度
        double dLon = Math.toRadians(b.lng - a.lng); // 经度差转换为弧度
        double _a = Math.pow(Math.sin(dLat / 2), 2) + Math.cos(Math.toRadians(a.lat)) * Math.cos(Math.toRadians(b.lat)) * Math.pow(Math.sin(dLon / 2), 2);
        double c = 2 * Math.atan2(Math.sqrt(_a), Math.sqrt(1 - _a)); // 中心角（单位：弧度）
        return R * c; // 距离（单位：千米）
    }

}
